﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace SJKP.PDFConversion.Extensions
{
    /// <summary>
    /// Extension methods for <see cref="SPDocumentLibrary"/>.
    /// </summary>
    public static class SPDocumentLibraryExtensions
    {
        /// <summary>
        /// Uploads a file to a document library, overwrite existing copies. 
        /// </summary>
        /// <param name="list">The libary to upload to</param>
        /// <param name="filedata">File content</param>
        /// <param name="fileName">The name of the file</param>
        public static void UploadFile(this SPDocumentLibrary list, byte[] filedata, string fileName)
        {
            if (list == null)
                throw new ArgumentNullException("list");
            string url = list.RootFolder.Url + "/" + fileName;
            SPFile file = null;
            if (list.ForceCheckout)
            {
                try
                {
                    file = list.RootFolder.Files[url];
                }
                catch(ArgumentException)
                {
                    //File not there;
                }
                if (file!=null && file.CheckOutType == SPFile.SPCheckOutType.None)
                {
                    file.CheckOut();
                }
            }
            file = list.RootFolder.Files.Add(url, filedata, true);
            if (file.CheckOutType != SPFile.SPCheckOutType.None)
                file.CheckIn("Uploaded by pdf conversion");
            if (list.EnableModeration)
                file.Approve("Approved by pdf conversion");
            list.Update();
        }
    }
}
